import {
  BOX,
  colNumber,
  content,
  correct,
  PLAYER,
  rowNumber,
  SPACE,
  WALL,
} from "./map.js";

/**
 * 按照指定的方向，让玩家移动一步
 * @param {*} direction left、right、up、down
 */
export function playerMove(direction) {
  const playerPoint = getPlayerPoint();
  const nextInfo = getPlayerNextInfo(
    playerPoint.row,
    playerPoint.col,
    direction
  );

  if (nextInfo.value === WALL) {
    return false;
  }

  // 能移动
  if (nextInfo.value === SPACE) {
    exchange(playerPoint, nextInfo);
    return true;
  } else {
    // 下一个位置是箱子
    // 获取箱子的下一个位置
    const nextNextInfo = getPlayerNextInfo(
      nextInfo.row,
      nextInfo.col,
      direction
    );
    if (nextNextInfo.value === SPACE) {
      exchange(nextInfo, nextNextInfo);
      exchange(playerPoint, nextInfo);
      return true;
    } else {
      return false;
    }
  }
}

function exchange(point1, point2) {
  var temp = content[point1.row][point1.col];
  content[point1.row][point1.col] = content[point2.row][point2.col];
  content[point2.row][point2.col] = temp;
}

/**
 * 得到玩家的位置
 */
function getPlayerPoint() {
  for (let row = 0; row < rowNumber; row++) {
    for (let col = 0; col < colNumber; col++) {
      if (content[row][col] === PLAYER) {
        return {
          row,
          col,
        };
      }
    }
  }
}

/**
 * 得到玩家在指定方向上下一个位置的信息（第几行，第几列，方向）
 * @param {Number} row 第几行
 * @param {Number} col 第几列
 * @param {Number} direction 改变的方向
 */
function getPlayerNextInfo(row, col, direction) {
  if (direction === "left") {
    return {
      row,
      col: col - 1,
      value: content[row][col - 1],
    };
  } else if (direction === "right") {
    return {
      row,
      col: col + 1,
      value: content[row][col + 1],
    };
  } else if (direction === "up") {
    return {
      row: row - 1,
      col: col,
      value: content[row - 1][col],
    };
  } else {
    return {
      row: row + 1,
      col: col,
      value: content[row + 1][col],
    };
  }
}

export function isMin() {
  return correct.every((e) => content[e.row][e.col] === BOX);
}
